package kuaishou

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"time"
)

const (
	ServerUrl = "https://open.kwaixiaodian.com"
)

//
type Client struct {
	options ClientOptions
}

//
func NewClient(options ...ClientOption) *Client {
	opts := NewClientOptions(options...)
	client := &Client{
		options: opts,
	}
	return client
}

func (c *Client) Do(requester Requester, responser Responser) (err error) {
	// request
	method := requester.RequestMethod()
	rawUrl := ServerUrl + requester.RequestPath()
	u, err := url.Parse(rawUrl)
	if err != nil {
		return err
	}

	buf, err := json.Marshal(requester)
	if err != nil {
		return err
	}
	body := bytes.NewBuffer(buf)

	urlValues := url.Values{}
	urlValues.Set("appkey", c.options.AppKey)
	urlValues.Set("method", requester.ApiName())
	urlValues.Set("version", "1")
	//urlValues.Set("param", bytes.NewBuffer(buf).String())
	urlValues.Set("param", "{}")
	urlValues.Set("access_token", c.options.AccessToken)
	timestamp := time.Now().UnixNano() / 1e6
	fmt.Println("timestamp:", timestamp)
	urlValues.Set("timestamp", fmt.Sprint(timestamp))
	u.RawQuery = urlValues.Encode()
	fmt.Println("url:", u.String())

	// request
	req, err := http.NewRequest(method, u.String(), body)
	if err != nil {
		return err
	}
	req.Header.Set("Authentication", c.options.AccessToken)
	fmt.Printf("req:%+v", req)

	// response
	client := http.DefaultClient

	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	err = json.NewDecoder(resp.Body).Decode(responser)
	if err != nil {
		return err
	}
	return
}
